<!--页面组件-->
<template>
  <div class="productLine">
    <div class="tempxyz rightTable" style="display: flex">
      <CCard class="leftTree">
        <CCardHeader>
          <!-- <Poptip trigger="hover" title v-if="showTips"> -->
          <CButton
            v-if="showTips"
            title="请先选择流程线分类"
            @click="addProductionLine"
            color="info"
            class="btnstyle textBtnStyle system-btn-style"
            data-permission="Btn_QuaCheckFlow_AddP"
          >
            <CIcon name="cil-plus" />&nbsp;流程线
          </CButton>

          <CButton
            v-else
            @click="addProductionLine"
            color="info"
            class="btnstyle textBtnStyle system-btn-style"
            v-show="before_hide"
            data-permission="Btn_QuaCheckFlow_AddP"
          >
            <CIcon name="cil-plus" />&nbsp;流程线
          </CButton>
          <CButton
            title="排序"
            color="info"
            class="btnstyle textBtnStyle system-btn-style"
            @click="dragSortClick('tree')"
            :disabled="!disableButton"
            :class="{ disableTextBtn: !disableButton }"
            data-permission="Btn_QuaCheckFlow_Sort"
          >
            排序
          </CButton>
          <CButton
            horizontal
            title="添加同级"
            variant="outline"
            class="leftTextBtnStyle system-btn-style"
            @click="addTreeNode"
            data-permission="Btn_QuaCheckFlow_AddSC"
          >
            <CIcon name="cil-plus" />同级
          </CButton>
          <CButton
            title="添加子级"
            variant="outline"
            class="leftTextBtnStyle system-btn-style"
            @click="addCatalog"
            data-permission="Btn_QuaCheckFlow_AddC"
          >
            <CIcon name="cil-plus" />子级
          </CButton>

          <CButton
            title="编辑"
            variant="outline"
            class="leftTextBtnStyle system-btn-style"
            @click="update"
            data-permission="Btn_QuaCheckFlow_UpC"
          >
            编辑
          </CButton>
          <CButton
            title="删除"
            variant="outline"
            class="leftTextBtnStyle system-btn-style"
            @click="delTreeNode"
            data-permission="Btn_QuaCheckFlow_DelC"
          >
            删除
          </CButton>
        </CCardHeader>
        <CCardBody
          class="cbodystyle"
          style="height: calc(100% - 125px) !important"
        >
          <div>
            <Tree
              :render="renderContent"
              :data="treeData"
              ref="tree"
              @on-select-change="selectTree"
              style="padding-top: 4px; padding-left: 20px"
            ></Tree>
          </div>
        </CCardBody>
      </CCard>

      <CCard class="rightCard">
        <CCardHeader class="header-wraper">
          <div class="header-left-titleWraper">
            <span class="liuchengName workflow"
              >流程列表：{{ this.productLineName }}</span
            >
          </div>
          <div class="header-right-wraper">
            <div class="search-wrapper">
              <CInput
                maxlength="50"
                placeholder="按生产线名称搜索..."
                v-model="workFlowName"
                class="input-search-style"
                @keyup.enter="enterfaction"
              />

              <CButton
                @click="enterfaction"
                color="info"
                class="header-search system-btn-style"
              >
                搜索
                <!-- <CIcon
                  name="cil-magnifying-glass"
                  style="height: 14px; width: 14px"
                />&nbsp; -->
              </CButton>
            </div>
            <CButton
              title="排序"
              color="info"
              size="sm"
              class="header-main-btn system-btn-style"
              @click="dragSortClick('table')"
              :disabled="disableButton"
              :class="{ disableTextBtn: disableButton }"
              data-permission="Btn_QuaCheckFlow_Sort"
            >
              排序
            </CButton>
            <Upload
              :before-upload="recoverWorkflow"
              :show-upload-list="false"
              class="uploader-wraper"
              action="#"
            >
              <Button
                type="primary"
                icon="ios-cloud-upload-outline"
                class="system-btn-style"
                >导入流程</Button
              >
            </Upload>
          </div>
        </CCardHeader>
        <CCardBody class="card-body">
          <div style="height: calc(100% - 45px)">
            <TableList
              ref="table"
              :getColumn="getColumns"
              :getAxios="getAxios"
              :allDataList.sync="allDataList"
            >
              <template v-slot:hierarchies="item">
                <span>{{ item.data.row.hierarchies[1].groupName }}</span>

                <span v-if="item.data.row.hierarchies[2]">
                  >>{{ item.data.row.hierarchies[2].groupName }}</span
                >
              </template>

              <template v-slot:show_details="item">
                <CButton
                  title="查看"
                  variant="outline"
                  class="textBtnStyle onButton system-btn-style"
                  @click="
                    displayProductionLineGraph(item.data.row, item.data.index)
                  "
                  >查看</CButton
                >
                <CButton
                  title="编辑"
                  variant="outline"
                  class="textBtnStyle onButton system-btn-style"
                  @click="updateProductionLine(item.data.row, item.data.index)"
                  data-permission="Btn_ProcessFlow_UpP"
                  >编辑</CButton
                >
                <CButton
                  title="复制"
                  variant="outline"
                  class="textBtnStyle onButton system-btn-style"
                  @click="copyProductBtn(item.data.row, item.data.index)"
                  data-permission="Btn_ProcessFlow_CpP"
                  >复制</CButton
                >
                <CButton
                  title="迁移"
                  variant="outline"
                  class="textBtnStyle onButton system-btn-style"
                  @click="moveProduction(item.data.row)"
                  data-permission="Btn_ProcessFlow_TransP"
                  >迁移</CButton
                >
                <CButton
                  title="导出"
                  variant="outline"
                  class="textBtnStyle onButton system-btn-style"
                  @click="downloadProduction(item.data.row)"
                  data-permission="Btn_ProcessFlow_TransP"
                  >导出</CButton
                >
                <CButton
                  title="删除"
                  variant="outline"
                  class="textBtnStyle onButton system-btn-style"
                  @click="delProduct(item.data.row, item.data.index)"
                  data-permission="Btn_ProcessFlow_DelP"
                  >删除</CButton
                >
              </template>
            </TableList>
          </div>
        </CCardBody>
      </CCard>
    </div>

    <Modal
      v-model="copyProduct"
      draggable
      scrollable
      :styles="modalStyle"
      title="复制生产线"
    >
      <p slot="header" class="modalHeader">复制生产线</p>
      <div class="modal-row-Wraper">
        <span class="liuchengName">名称：</span>
        <CInput v-model="proFlowName" style="width: 180px" />
      </div>
      <div class="modal-row-Wraper">
        <span class="liuchengName">版本：</span>
        <input
          type="text"
          class="input-control"
          value
          placeholder="请输入正整数"
          v-model="version"
          onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^0-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
          onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^0-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
        />
      </div>
      <template #footer class="footerBtns">
        <CButton @click="copProductCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="coplProductOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="delShow"
      draggable
      scrollable
      :styles="modalStyle"
      title="删除生产线分类"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/shanchu.svg" alt />
        <span>删除生产线分类</span>
      </p>
      <div class="modalBody">
        <p>删除生产线分类时与生产线分类相关的信息都会丢失</p>
        <p>请确认是否删除?</p>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="delCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="delOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="delProductShow"
      draggable
      scrollable
      :styles="modalStyle"
      title="删除生产线"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/shanchu.svg" alt />
        <span>删除生产线</span>
      </p>
      <div class="modalBody">
        <p>删除生产线时与生产线分类相关的信息都会丢失</p>
        <p>请确认是否删除?</p>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="delProductCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="delProductOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="addShow"
      draggable
      scrollable
      :styles="modalStyle"
      title="新建生产线分类"
    >
      <p slot="header" class="modalHeader">新建生产线分类</p>
      <CRow>
        <CCol md="12">
          <CForm>
            <CSelect
              label="标签"
              horizontal
              :options="labelList"
              :value.sync="addData.label"
              placeholder="请输入标签"
            ></CSelect>
            <CInput
              label="流程分类"
              placeholder="请输入流程分类"
              horizontal
              v-model="addData.groupname"
            />
            <CTextarea
              label="类别描述"
              v-model="addData.description"
              placeholder="请输入类别描述"
              horizontal
              rows="5"
            />
          </CForm>
        </CCol>
      </CRow>
      <template #footer class="footerBtns">
        <CButton @click="addCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="addOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal v-model="moveProduct" draggable scrollable title="迁移生产线">
      <p slot="header" class="modalHeader">迁移生产线</p>
      <CCardBody>
        <Tree
          :data="treeDataOfMove"
          class="scrollBar"
          ref="resTree"
          @on-select-change="moveTree"
        ></Tree>
      </CCardBody>
      <template #footer class="footerBtns">
        <CButton @click="moveCancle" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="moveOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="updateShow"
      draggable
      scrollable
      :styles="modalStyle"
      title="更新生产线分类"
    >
      <p slot="header" class="modalHeader">更新生产线分类</p>
      <CRow>
        <CCol md="12">
          <CForm>
            <CSelect
              label="标签"
              horizontal
              :options="labelList"
              :value.sync="upData.label"
              placeholder="请输入标签"
            ></CSelect>
            <CInput
              label="流程分类"
              placeholder="请输入流程分类"
              horizontal
              v-model="upData.groupname"
            />
            <CTextarea
              label="类别描述"
              v-model="upData.description"
              placeholder="请输入类别描述"
              horizontal
              rows="3"
            />
          </CForm>
        </CCol>
      </CRow>
      <template #footer class="footerBtns">
        <CButton @click="updateCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="updateOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="importClassifyModal"
      draggable
      scrollable
      title="选择导入分类"
    >
      <p slot="header" class="modalHeader">选择导入分类</p>
      <div class="productionLineClassifyTreeDiv">
        <ul id="productionLineClassifyTree" class="ztree customStyleZtree"></ul>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="classifyCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="classifyOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>

    <ProductionLineGraph
      ref="refProductionLineGraphModal"
      v-show="productionLineGraphModal"
      :modalShow="productionLineGraphModal"
      @close="productionLineGraphModalClose"
    ></ProductionLineGraph>

    <!--排序弹框-->
    <sort-delog
      ref="sortDelog"
      :dragSortProp="dragSortDdata"
      :SortDdata.sync="sortData"
      :confirmData="confirmData"
    >
    </sort-delog>
  </div>
</template>

<!--js代码-->
<script>
const items = [];
import axios from "axios";
import TableList from "@/template/table/TableList";
import ProductionLineGraph from "../../views/jobProcess/processingGraph";
import sortDelog from "../../template/sortDelog/sortDelog";
export default {
  name: "qcProductionLineModel",
  components: {
    TableList,
    ProductionLineGraph,
    sortDelog,
  },
  props: {},
  data() {
    return {
      taskType: 1,
      isAddSameClassify: false,
      productionLineGraphModal: false,
      modalStyle: { top: "340px" },
      classifyWorkFlowformData: "",
      importClassifyModal: false,
      currentPage: 1,
      productLineName: "所有流程",

      pageSize: 15,
      showimgsearchicon: true,
      showimgofficon: false,
      isHaveProLine: true,

      before_hide: false,
      showTips: true,
      delProductShow: false,
      clickGetId: "",
      children: false,
      treeData: [],
      delShow: false,
      updateShow: false,
      addShow: false,
      productId: "",
      copyProduct: false,
      pid: -1,
      addData: {
        id: 0,
        description: "",
        groupname: "",
        parentid: "",
        label: "image",
      },
      upData: {
        id: 0,
        description: "",
        groupname: "",
        parentid: "",
        label: "",
      },
      updateProductionLines: false,
      items: items.map((item, id) => {
        return { ...item, id };
      }),

      details: [],
      collapseDuration: 0,
      picture: "",
      workFlowName: "",
      proFlowName: "",
      version: "",
      treeDataOfMove: [],
      moveProduct: false,
      groupId: 0,
      oldId: 0,
      labelList: [
        {
          value: "image",
          label: "影像",
        },
        {
          value: "parameter",
          label: "参量",
        },
      ],

      getColumns: [
        {
          title: "流程名称",
          key: "workflowName",
          minWidth: 200,
        },
        {
          title: "流程描述",
          key: "description",
          minWidth: 200,
        },
        {
          title: "流程分类",
          key: "hierarchies",
          slot: "hierarchies",
          width: 120,
          className: "centerText",
        },
        {
          title: "版本",
          key: "workflowVersion",
          width: 70,
          className: "centerText",
        },
        {
          title: "创建时间",
          key: "createTime",
          width: 170,
          className: "centerText",
        },
        {
          title: "修改时间",
          key: "updateTime",
          width: 170,
          className: "centerText",
        },
        {
          title: "操作",
          key: "show_details",
          slot: "show_details",
          className: "centerText",
          width: 360,
        },
      ],
      getAxios: {
        url: this.$api.modelApi.search, //请求路径
        method: "get", //请求方式
        dataList: { groupId: 1 }, //请求参数
      },

      /*排序*/
      dragSortDdata: [], //需要排序的数据
      disableButton: true,
      currentClickItemId: "", //当前点击对象
      sortData: [], //已经拍好顺序的
      allDataList: {}, //所有的表格数据
      confirmData: {
        forName: "title",
        type: "tree",
        url: this.$api.modelApi.groupSort, //树排序
      },
    };
  },
  computed: {
    getColumn() {
      return [
        {
          key: "num",
          title: "序号",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "div",
                {
                  style: {
                    display: "inline-block",
                    width: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  },
                  domProps: {
                    title: params.row.num,
                  },
                  props: {
                    color: "info",
                    variant: "outline",
                  },
                },
                params.row.num
              ),
            ]);
          },
        },
        {
          key: "workflowName",
          title: "流程名称",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "div",
                {
                  style: {
                    display: "inline-block",
                    width: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  },
                  domProps: {
                    title: params.row.workflowName,
                  },
                  props: {
                    color: "info",
                    variant: "outline",
                  },
                },
                params.row.workflowName
              ),
            ]);
          },
        },
        {
          key: "description",
          title: "流程描述",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "div",
                {
                  style: {
                    display: "inline-block",
                    width: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  },
                  domProps: {
                    title: params.row.description,
                  },
                  props: {
                    color: "info",
                    variant: "outline",
                  },
                },
                params.row.description
              ),
            ]);
          },
        },
        {
          key: "groupName",
          title: "流程分类",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "div",
                {
                  style: {
                    display: "inline-block",
                    width: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  },
                  domProps: {
                    title: params.row.workflowName,
                  },
                  props: {
                    color: "info",
                    variant: "outline",
                  },
                },
                params.row.workflowName
              ),
            ]);
          },
        },
        {
          key: "createTime",
          title: "创建时间",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "div",
                {
                  style: {
                    display: "inline-block",
                    width: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  },
                  domProps: {
                    title: params.row.createTime,
                  },
                  props: {
                    color: "info",
                    variant: "outline",
                  },
                },
                params.row.createTime
              ),
            ]);
          },
        },
        {
          key: "updateTime",
          title: "修改时间",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "div",
                {
                  style: {
                    display: "inline-block",
                    width: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  },
                  domProps: {
                    title: params.row.updateTime,
                  },
                  props: {
                    color: "info",
                    variant: "outline",
                  },
                },
                params.row.updateTime
              ),
            ]);
          },
        },
        {
          title: "操作",
          width: "350px",
          slot: "action",
          align: "center",
        },
      ];
    },
  },
  mounted() {
    // 查询子任务页面返回调用
    if (this.$route.query.from === "updateWorkflow") {
      if (this.workFlowName == "") {
        this.currentPage = parseInt(this.$route.query.pageNum);
      } else {
        this.workFlowName = this.$route.query.workflowName;
        this.enterfaction();
      }
    }
    this.getModelCategoryTree();
    /*this.getProduct(1);*/
  },
  methods: {
    //打开排序弹框
    dragSortClick(data) {
      let that = this;
      this.$refs.sortDelog.openOrClose();
      if (data === "table") {
        that.confirmData = {
          forName: "workflowName",
          type: "table",
          url: this.$api.modelApi.sort,
        };
        //获取表格数据
        let path = that.$api.modelApi.search;
        let param = {
          pageNum: "",
          pageSize: "",
          groupId: that.currentClickItemId,
        };
        let getAxiosData = {
          method: "get",
          url: path,
        };
        that.$refs.table.exportTableData(param, getAxiosData);
      }
      if (data === "tree") {
        that.confirmData = {
          forName: "title",
          type: "tree",
          url: this.$api.modelApi.groupSort,
        };
      }
    },
    selectTree(data, item) {
      let self = this;
      self.productId = item.id;
      self.currentClickItemId = item.id;
      if (item.children.length) {
        self.dragSortDdata = item.children;
        self.disableButton = true;
        this.children = true;
      } else {
        self.dragSortDdata = [];
        self.disableButton = false;
        this.children = false;
      }

      if (item.workflowNum == 0) {
        self.isHaveProLine = false;
      } else {
        self.isHaveProLine = true;
      }

      self.workFlowName = "";
      self.productLineName = item.title;
      self.pid = item.parentId;

      this.getProduct(self.productId);
      this.clickGetId = self.productId;
      this.showTips = false;
      this.before_hide = true;
      this.currentPage = 1;
      this.customLabel = item.customLabel;
    },
    getModelCategoryTree() {
      let self = this;
      self.treeData = [];
      let path = this.$api.modelApi.groupTree;
      let param = {
        groupId: 1,
      };
      this.http.get(path, param).then((res) => {
        self.loading = false;
        if (res.status == 200) {
          if (res.data.data.length > 0) {
            self.treeData = res.data.data;
            // 质量检查一级树的默认展示关闭  start
            self.dragSortDdata = res.data.data;
            for (let j = 0; j < self.treeData.length; j++) {
              for (let i = 0; i < self.treeData.length; i++) {
                self.treeData[i].expand = false;
              }
              self.treeData[0].selected = false;
              // self.productId = self.treeData[j].id;
              self.pid = self.treeData[j].parentId;
              if (self.treeData[j].children.length > 0) {
                // 质量检查子级树的默认展示关闭 start
                for (let i = 0; i < self.treeData[0].children.length; i++) {
                  self.treeData[0].children[i].expand = false;
                }

                this.children = true;
              } else {
                this.children = false;
              }
            }
          } else {
            self.productId = "";
            self.pid = "0";
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    //获取流程线列表
    getProduct(groupId) {
      // 点击查看所有流程按钮，改变流程列表后的文字
      if (groupId == 1) {
        this.productLineName = "所有流程";
      }
      let self = this;
      // let date = this.$moment().format("YYYY-MM-DD");
      let path = this.$api.modelApi.search;
      let param = {
        groupId: groupId,
        pageNum: self.currentPage,
        pageSize: this.pageSize,
        workflowName: this.workFlowName,
      };

      let getAxiosData = {
        method: "get",
        url: path,
      };
      this.$refs.table.getRefreshTable(param, getAxiosData);
    },

    getVendorId(event) {
      let tempdata = event.target.value; //获取option对应的value值
      this.pageSize = parseInt(tempdata);
    },
    enterfaction() {
      // 搜索算法列表显示搜索的关键字
      this.productLineName = this.workFlowName;
      this.search();
    },
    clearmess() {
      this.workFlowName = "";
      this.searchAllProductionLine();
    },
    // tree 提示信息 start
    renderContent(h, { root, node, data }) {
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            width: "100%",
            cursor: "pointer",
          },
          on: {
            click: () => {
              /*  this.clickTree1(data);*/
            },
          },
        },
        [
          h(
            "Tooltip",
            {
              props: {
                placement: "right-end",
                transfer: true,
              },
            },
            [
              data.title, //控制树形显示的内容
              h(
                "span",
                {
                  slot: "content",
                  style: {
                    whiteSpace: "normal",
                  },
                },
                data.title //控制Tooltip显示的内容
              ),
            ]
          ),
          h("span", {
            style: {
              display: "inline-block",
              float: "right",
              marginRight: "32px",
            },
          }),
        ]
      );
    },
    // end
    // 获取流程对应的流程图
    displayProductionLineGraph(row, index) {
      this.picture = this.$api.modelApi.loopUpGraph + row.id + "/findPicture";
      this.productionLineGraphModal = true;
      this.$refs.refProductionLineGraphModal.displayProductionLineGraph(
        this.picture
      );
    },
    productionLineGraphModalClose() {
      this.productionLineGraphModal = false;
    },

    // 更新生产线
    updateProductionLine(row, index) {
      // this.$router.push({ path: `/updateWorkflow/${row.id}`+ "?" + row.num, });
      if (!this.customLabel) {
        let path = this.$api.modelApi.groupLabel + row.id + "/groupLabel";
        this.http.get(path).then((res) => {
          if (res.data.code == 0) {
            this.customLabel = res.data.data.label;
          } else {
            this.customLabel = "";
          }
          this.updateProductionLineUrl(row);
        });
      } else {
        this.updateProductionLineUrl(row);
      }
    },

    updateProductionLineUrl(row) {
      this.$router.push({
        path: `/updateWorkflow/${row.id}`,
        query: {
          pageNum: this.currentPage,
          type: this.customLabel,
          from: "qcProductionLineModel",
        },
      });
    },

    toggleDetails(item) {
      this.$set(this.items[item.id], "_toggled", !item._toggled);
      this.collapseDuration = 300;
      this.$nextTick(() => {
        this.collapseDuration = 0;
      });
    },

    //删除流程
    delProduct(row, index) {
      this.delProductShow = true;
      this.clickId = row.id;
    },
    delProductCancel() {
      this.delProductShow = false;
    },
    delProductOk() {
      this.delProductShow = false;
      let path = this.$api.modelApi.deleteWorkflow + this.clickId;
      let param = {};
      this.http.delete(path, param).then((res) => {
        if (res.data.code == 0) {
          this.getProduct(this.productId);
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    copyProductBtn(row, index) {
      this.copyProduct = true;
      this.clickId = row.id;
      // 点击复制初始化赋值弹窗
      this.proFlowName = row.workflowName;
      this.version = row.workflowVersion;
    },
    copProductCancel() {
      this.copyProduct = false;
    },
    //复制流程
    coplProductOk() {
      this.copyProduct = false;
      let workflowId = this.clickId;
      let path = this.$api.modelApi.copyProductionLine + workflowId + "/copy";
      let params = {
        workflowName: this.proFlowName,
        workflowVersion: this.version,
        userId: sessionStorage.getItem("userId"),
        // _loadingContainer: document.querySelector(".c-main"),
      };
      this.http.get(path, params).then((res) => {
        if (res.data.code == 0) {
          this.getProduct(this.productId);
          this.$Message.success("复制成功");
        } else {
          this.$Message.error("流程已存在");
        }
      });
    },

    //下载流程
    downloadProduct(row, index) {
      let workflowId = row.id;
      let path =
        this.$api.modelApi.downLoadProductionLine + workflowId + "/download";
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          this.$Message.success(res.data.message);
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    // 根据生产线名称搜索
    search() {
      let workFlowName = this.workFlowName.trim();
      let path = this.$api.modelApi.search;

      let param = {
        // groupId: this.productId == undefined ? 1 : this.productId,
        workflowName: workFlowName,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      };

      if (workFlowName == "") {
        this.$Message.warning("请输入查询生产线名称");
        return;
      }

      let getAxiosData = {
        method: "get",
        url: path,
      };
      this.$refs.table.getRefreshTable(param, getAxiosData);
    },
    //查看所有流程
    searchAllProductionLine() {
      let self = this;
      let path = this.$api.modelApi.search;

      let param = {
        workflowName: self.workFlowName,
        pageNum: self.currentPage,
        pageSize: self.pageSize,
      };

      let getAxiosData = {
        method: "get",
        url: path,
      };
      this.$refs.table.getRefreshTable(param, getAxiosData);
    },

    update() {
      this.updateShow = true;
      this.upData.groupname = this.$refs.tree.getSelectedNodes()[0].title;
      this.upData.description =
        this.$refs.tree.getSelectedNodes()[0].description;
      this.upData.label = this.$refs.tree.getSelectedNodes()[0].customLabel;
    },
    updateCancel() {
      this.updateShow = false;
    },
    delTreeNode() {
      this.delShow = true;
      this.clickId = this.$refs.tree.getSelectedNodes()[0].id;
      if (this.$refs.tree.getSelectedNodes()[0].children.length > 0) {
        this.children = true;
      } else {
        this.children = false;
      }
    },
    delCancel() {
      this.delShow = false;
    },
    addTreeNode() {
      this.addShow = true;
      this.isAddSameClassify = true;
    },

    addCatalog() {
      if (this.isHaveProLine) {
        this.$Message.warning("不能在有流程的节点下增加子节点！");
      } else {
        this.addShow = true;
      }
    },
    addCancel() {
      this.addShow = false;
    },
    delOk() {
      let self = this;
      if (!self.productId) {
        this.$Message.warning("请先选择要删除的数据");
        return;
      }
      if (self.children || self.pid == 0) {
        this.$Message.warning("有子节点不能删除||根节点不能删除");
        return;
      }
      self.delShow = false;
      let path = this.$api.modelApi.deleteWorkflow + this.productId + "/group";
      this.http.delete(path).then((res) => {
        if (res.status == 200) {
          this.$Message.success("删除成功");
          this.getModelCategoryTree();
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    addOk() {
      let self = this;
      let path = this.$api.modelApi.productLine;
      if (!self.addData.groupname) {
        this.$Message.warning("请输入流程分类！");
        return;
      }
      //添加同级时区别productId没值时；
      if (this.isAddSameClassify) {
        if (!self.productId) {
          self.productId = 1; //表示在质检大类下
        } else {
          self.productId = this.$refs.tree.getSelectedNodes()[0].parentId;
        }
      }

      self.addData.parentid = self.productId;

      let param = self.addData;
      this.http.post(path, param).then((res) => {
        if (res.status == 200) {
          this.getModelCategoryTree();
          this.$Message.success("创建成功");
        } else {
          this.$Message.error(res.data.message);
        }
      });
      self.addShow = false;
      this.isAddSameClassify = false;
      self.addData = {
        id: 0,
        description: "",
        groupname: "",
        parentid: "",
        label: "image",
      };
    },
    updateOk() {
      let self = this;
      if (!self.productId) {
        this.$Message.warning("没有选择要更新的节点");
        return;
      }
      self.updateShow = false;
      let path = this.$api.modelApi.updateGroupById;
      self.upData.id = self.productId;
      self.upData.parentid = self.pid;
      let param = self.upData;
      this.http.post(path, param).then((res) => {
        if (res.status == 200) {
          this.$Message.success("更新成功");
          this.getModelCategoryTree();
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    addProductionLine(id) {
      if (
        id == "" ||
        this.$refs.tree.getSelectedNodes()[0].children.length != 0
      ) {
        this.$Message.warning(
          "该节点下有子分类，不能同时包含流程线，请选择不包含分类的子节点！"
        );
        return;
      } else {
        let routerLink = `/createWorkflow/${this.clickGetId}`;
        this.$router.push({
          path: routerLink,
          query: {
            taskType: this.taskType,
            type: this.$refs.tree.getSelectedNodes()[0].customLabel,
          },
        });
      }
    },

    downloadProduction(item) {
      let _this = this;
      let path = _this.$api.modelApi.downloadWorkflow;

      window.location.href =
        path +
        "?workflowName=" +
        item.workflowName +
        "&workflowVersion=" +
        item.workflowVersion;
    },
    recoverWorkflow(file) {
      let _this = this;
      var formData = new window.FormData();
      formData.append("file", file);
      _this.classifyWorkFlowformData = formData;

      _this.importClassifyModal = true;
      _this.initClassifyZtree();
    },

    initClassifyZtree() {
      let _this = this;
      let setting = {
        // check: {
        //   enable: true,
        //   nocheckInherit: false,
        //   chkboxType: { Y: "s", N: "ps" }, //级联  //{ Y: "", N: "" },
        // },
        data: {
          simpleData: {
            enable: true,
          },
          key: {
            name: "title", //将ztree显示的name的数据设置位title
          },
        },
        view: {
          showLine: false,
          showIcon: false,
        },
        callback: {
          onClick: this.zTreeClassifyOnClick,
        },
      };

      $.fn.zTree.init(
        $("#productionLineClassifyTree"),
        setting,
        _this.treeData
      );
    },
    zTreeClassifyOnClick(event, treeId, treeNode) {
      if (treeNode.children.length > 0) {
        this.$Message.warning("该节点已包含分组，不能同时包含流程线！");
      }
    },
    classifyOk() {
      let _this = this;
      let treeObj = $.fn.zTree.getZTreeObj("productionLineClassifyTree");
      let sNodes = treeObj.getSelectedNodes();
      if (sNodes.length < 1) {
        if (confirm("不选择分类将会按照工作流默认的分类导入，是否默认？")) {
          _this.importClassifyModal = false;
          _this.importWorkflow(groupId);
        }
        return;
      }

      let groupId = parseInt(sNodes[0].id);
      if (groupId === 0 || groupId === 1 || groupId === 2) {
        //文件夹以及大目录
        _this.$message.warning("请选择分类节点");
      } else {
        _this.importClassifyModal = false;
        _this.importWorkflow(groupId);
      }
    },
    importWorkflow(groupId) {
      let _this = this;
      let path = _this.$api.modelApi.recoverWorkflow;
      _this.classifyWorkFlowformData.append("groupId", groupId);
      axios
        .post(path, _this.classifyWorkFlowformData, {
          headers: { "Content-Type": "multipart/form-data" },
        })
        .then((res) => {
          if (res.data.code == 0) {
            _this.$Message.success("导入成功");
            /* 如果在根节点导入也没有选分类就默认刷新全部的
           如果 导入选择分类和左侧树选择相同时刷新表格；
           其他条件不刷新（待确认）
           */
            if (!groupId) {
              _this.getProduct(1);
            } else if (_this.productId) {
              _this.getProduct(_this.productId);
            }
            //  else if (parseInt(_this.productId) === groupId) {
            //   _this.getProduct(groupId);
            // }
          } else {
            this.$Message.error(res.data.message);
          }
        });
    },
    classifyCancel() {
      this.importClassifyModal = false;
    },

    moveProduction(item) {
      let self = this;
      self.moveProduct = true;
      self.treeDataOfMove = self.treeData;
      self.oldId = item.id;
    },
    moveCancle() {
      this.moveProduct = false;
    },

    moveOk() {
      let _that = this;
      if (!_that.groupId || _that.groupId == 1) {
        this.$Message.warning("请选择要迁移的生产线分类");
        return;
      }

      let path = this.$api.modelApi.loopUpGraph1;
      let groupId = parseInt(_that.groupId);
      axios({
        method: "PUT",
        url: path,
        contentType: "application/json",
        data: {
          groupId: groupId,
          id: _that.oldId,
        },
      }).then((res) => {
        if (res.data.code == 0) {
          _that.getProduct(_that.groupId);
          _that.$Message.success("迁移成功");
          _that.moveProduct = false;
        } else {
          _that.$Message.error(res.data.message);
        }
      });
    },
    moveTree() {
      let _self = this;
      if (_self.$refs.resTree.getSelectedNodes()[0].children.length > 0) {
        this.$Message.warning("流程分组不能同时包含流程线和分组！");
        _self.groupId = 1;
      } else {
        _self.groupId = _self.$refs.resTree.getSelectedNodes()[0].id;
      }
    },
  },
  watch: {
    items(newVal, oldVal) {
      this.$nextTick(function () {
        this.GlobalPermissionRender.render();
      });
    },
    pageSize(newVal, oldVal) {
      this.pageSize = newVal;
      this.getProduct(this.productId);
    },
    currentPage(newVal, oldVal) {
      this.currentPage = newVal;
      //获取流程线列表
      this.getProduct(this.productId);
    },
    workFlowName(newVal, oldVal) {
      if (newVal.length >= 50) {
        this.$Message.warning("任务名称长度不得超过50个字符");
      }
      if (newVal == "") {
        this.showimgsearchicon = true;
        this.showimgofficon = false;
      } else {
        this.showimgsearchicon = false;
        this.showimgofficon = true;
      }
    },
    period: function (newVal, oldVal) {
      const regex = /^([0-9]*[1-9][0-9]*(.[0-9]+)?|[0]+.[0-9]*[1-9][0-9]*)$/;
      if (!regex.test(newVal)) {
        //如果小于等于零
        this.period = oldVal; //恢复原值
      }
    },
    allDataList(newVal) {
      this.dragSortDdata = newVal.data.data;
    },
    sortData(newVal) {
      let that = this;
      if (newVal.length && newVal[0] === "table") {
        that.getProduct(that.currentClickItemId); //保存成功后重刷表格
      }
      if (newVal.length && newVal[0] !== "table") {
        if (that.currentClickItemId) {
          let flatten = (arr) => {
            arr.forEach((item) => {
              if (item["children"] && item["children"].length) {
                flatten(item["children"]);
              }
              if (item["id"] === that.currentClickItemId) {
                item["children"] = newVal;
                return;
              }
            });
            return arr;
          };
          that.treeData = flatten(that.treeData);
        } else {
          that.treeData = newVal;
        }
      }
    },
  },
};
</script>
<!--css样式-->
<style scoped>
.ivu-btn-primary {
  height: 35px;
}

.leftTree .ivu-tree {
  border-radius: 3px;
  margin-top: 10px;
  width: 100%;
}
.btnstyle {
  width: 90px !important;
  padding-top: 4px;
  height: 35px;
  margin-top: 6px;
  padding: 5px;
}

.leftTree {
  width: 280px;
}

.cbodystyle {
  width: 100%;
  margin-top: 60px;
  margin-bottom: 15px;
  overflow: auto;
}
.leftTree .card-body {
  padding: 0;
}
.ivu-tree-children {
  padding-top: 50px !important;
}
.ivu-tree ul {
  padding-top: 50px !important;
}

.table thead th {
  border-bottom: 0px;
}
.cardstyle {
  margin-right: 20px;
  margin-left: 23px;
  margin-top: 20px;
  overflow-y: auto;
  height: calc(100% - 63px);
}
.row {
  margin-left: 1px;
  margin-bottom: 20px;
  width: 100%;
}
.rightCard {
  width: 85%;
  margin-left: 10px;
}

.table-bordered thead th {
  text-align: center;
}

.table thead th {
  text-align: center;
}
.add {
  width: 90px;
  padding: 6px;
  height: 35px;
  margin-right: 8px;
}
.add:hover {
  background-color: #698cf7 !important;
}

.form-control:disabled,
.form-control[readonly] {
  background-color: #f5f5f5;
}
.modal-row-Wraper {
  display: flex;
}
.liuchengName {
  margin-left: 5px;
  margin-top: 5px;
  margin-right: 10px;
  font-size: 16px;
}
::-webkit-scrollbar {
  /* width: 3px;
  height: 3px; */
  background-color: #d8d8d8;
}
::-webkit-scrollbar-thumb {
  background-color: #7eb8ee;
}

.workflow {
  font-family: "微软雅黑";
  font-size: 18px;
}

.scrollBar {
  height: 60vh;
  overflow-y: auto;
}

.productionLineClassifyTreeDiv {
  max-height: 500px;
  overflow-x: auto;
  overflow-y: auto;
  margin-bottom: -16px;
  margin-right: -16px;
}

.leftTextBtnStyle {
  color: white;
  padding: 2px 8px;
  font-size: 14px;
  margin-top: 10px;
  margin-bottom: 0px;
  margin-left: 0px;
  margin-right: 2px;
  border-radius: 4px;
  cursor: pointer;
}

/deep/.ivu-table td.centerText {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
  text-align: -moz-center;
  text-align: -webkit-center;
}
.onButton:hover {
  color: white;
}

.theContainer-vue .body {
  overflow-y: hidden;
}

/*排序弹框*/
.dragSortStyle /deep/ .ivu-modal-body {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
}
.vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;
}
.dragBox {
  padding: 3px 10px 3px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.sortTableButton {
  width: 80px;
  height: 35px;
  padding: 8px;

  margin-right: 20px;
  margin-top: 0;
}
.input-control {
  height: 35px;
  width: 180px;
  padding: 0.375rem 0.75rem;
  border: 1px solid #d8dbe0;
  border-radius: 5px;
}
.input-control:focus {
  color: #768192;
  background-color: #fff;
  border-color: #958bef !important;
  outline: 0;
  -webkit-box-shadow: 0 0 0 0.2rem rgba(50, 31, 219, 0.25);
  box-shadow: 0 0 0 0.2rem rgba(50, 31, 219, 0.25);
}
</style>
